package com.datamation.swadeshi.control.data;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.datamation.swadeshi.model.FreeDet;

public class FreeDetDS {
	
	private SQLiteDatabase dB;
	private DatabaseHelper dbHelper;
	Context context;
	private String TAG="swadeshi";
	
	
	public FreeDetDS (Context context){
		this.context = context;
		dbHelper = new DatabaseHelper(context);
	}
	
	public void open() throws SQLException {
		dB = dbHelper.getWritableDatabase();
	}
	@SuppressWarnings("static-access")
	public int createOrUpdateFreeDet(ArrayList<FreeDet>  list) {
		
		int count =0;
		
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		Cursor cursor = null;
		
	try{
					
    for (FreeDet det : list) {
		
			ContentValues values = new ContentValues();
			
			values.put(dbHelper.FFREEDET_REFNO, 	det.getFFREEDET_REFNO());
			values.put(dbHelper.FFREEDET_ITEM_CODE, det.getFFREEDET_ITEM_CODE());
			values.put(dbHelper.FFREEDET_RECORD_ID, det.getFFREEDET_RECORD_ID());
								
			count = (int) dB.insert(dbHelper.TABLE_FFREEDET, null, values);

			}
		}catch (Exception e) {
		
			Log.v("Exception", e.toString());
	
		}finally {  
			if (cursor !=null) {
				cursor.close();
			}
			dB.close();
		}
		return count;
				
	}
	
	
	public int getAssoCountByRefno(String refno){
		
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		
		String selectQuery = "SELECT count(*) FROM " + dbHelper.TABLE_FFREEDET +" WHERE "+dbHelper.FFREEDET_REFNO+"='"+refno+"'";
		
		Cursor cursor = null;
		cursor = dB.rawQuery(selectQuery, null);
		
		while(cursor.moveToNext()){

			return cursor.getInt(0);
			
		}
		return 0;
		
	}
	
	public int deleteAll(){
		
		int count =0;
		
		if(dB == null){
			open();
		}else if(!dB.isOpen()){
			open();
		}
		Cursor cursor = null;
		try{
			
			cursor = dB.rawQuery("SELECT * FROM " + dbHelper.TABLE_FFREEDET, null);
			count =cursor.getCount();
			if(count>0){
				int success = dB.delete(dbHelper.TABLE_FFREEDET, null, null);
				Log.v("Success", success+"");
			}
		}catch (Exception e){

			Log.v(TAG+" Exception", e.toString());
			
		}finally{  
			if (cursor !=null) {
				cursor.close();
			}
			dB.close();
		}
		
		return count;
		
	}
}
